"use client";
import { useQueryClient, useQuery } from "@tanstack/react-query";
import * as z from "zod";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "sonner";
import { CreateCookieSchema } from "@/schemas";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { IPlatform, IFormRef } from "../types";
import { CookiesForm } from "./_components/form";
export type CookieDialogProps = {
  hastrigger: boolean;
  open: boolean;
  platform: IPlatform | null;
  setOpenAction: (value: boolean) => void;
};

export function CookieDialog({
  hastrigger,
  open,
  platform,
  setOpenAction,
}: CookieDialogProps) {
  const queryClient = useQueryClient();
  const formRef = useRef<IFormRef>(null);

  const form = useForm<z.infer<typeof CreateCookieSchema>>({
    resolver: zodResolver(CreateCookieSchema),
    defaultValues: {
      name: "tb",
      platformId: platform?.id || 0,
    },
  });
  useEffect(() => {
    form.setValue("platformId", platform?.id || 0);
  }, [platform, form]);
  const handleSubmit = async (data: z.infer<typeof CreateCookieSchema>) => {
    try {
      const formData = new FormData();
      formData.append("file", data.file);
      formData.append("platformId", data.platformId.toString());
      formData.append("name", data.name);
      console.log("handlesubmit", data);
      const resp = await fetch("/api/cookies/upload", {
        method: "POST",
        credentials: "include",
        body: formData,
      });

      if (!resp.ok) {
        const errorData = await resp.json();
        toast.error(
          `Cookies creation failed: ${errorData.message || resp.statusText}`,
        );
        return;
      }

      toast.info("Cookies create successful!");
      queryClient.invalidateQueries(); // Invalidate only the tasks query
      setOpenAction(false);
    } catch (error) {
      toast.error(
        `Cookies creation failed: ${error || "An unexpected error occurred."}`,
      );
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpenAction}>
      {hastrigger ? (
        <DialogTrigger asChild>
          <Button variant="link">新增cookie</Button>
        </DialogTrigger>
      ) : null}
      <DialogContent className="max-w-fit">
        <DialogHeader className="flex">
          <DialogTitle className="flex justify-center w">
            新增cookie
          </DialogTitle>
          <DialogDescription></DialogDescription>
        </DialogHeader>
        <CookiesForm
          handleSubmit={handleSubmit}
          platform={platform}
          ref={formRef}
        />

        <DialogFooter className="sm:justify-end">
          <Button
            variant={"link"}
            key={"submit"}
            onClick={async () => {
              formRef.current?.onSubmit();

              // const result = await form.trigger();
              // console.log(form.getValues());
              // if (result) setOpenAction(false);
            }}
          >
            Submit
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
